package com.fsquare.web.processor;

import java.text.NumberFormat;

import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.broadleafcommerce.core.web.processor.PriceTextDisplayProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.standard.expression.StandardExpressionProcessor;

import com.fsquare.component.CurrencySymbolsWrapper;

//@Component("blPriceTextDisplayProcessor")
public class CustomPriceTextDisplayProcessor extends PriceTextDisplayProcessor{
	
	@Autowired
	private CurrencySymbolsWrapper currencySymbolsWrapper;
	
	public CustomPriceTextDisplayProcessor() {
        super();
    }
	
	@Override
    protected String getText(Arguments arguments, Element element, String attributeName) {
        
        Money price;
        
        try {
            price = (Money) StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue(attributeName));
        } catch (ClassCastException e) {
            Number value = (Number) StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue(attributeName));
            price = new Money(value.doubleValue());
        }

        if (price == null) {
            return "Not Available";
        }

        BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
        if (brc.getJavaLocale() != null) {
            NumberFormat format = NumberFormat.getCurrencyInstance(brc.getJavaLocale());
//            format.setCurrency(price.getCurrency());
//            return format.format(price.getAmount());
            
           String currencySymbol = currencySymbolsWrapper.getCurrencySymbol(price.getCurrency());
            
//          format.setCurrency(price.getCurrency());
//          return format.format(price.getAmount());
          
          return price.getAmount().toString()+" "+currencySymbol;
            
        } else {
            // Setup your BLC_CURRENCY and BLC_LOCALE to display a diff default.
//            return "$ " + price.getAmount().toString();
            return price.getAmount().toString()+" €";
        }
    }
}
